﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Fcdbas.Platform.Properties;
using Fcdbas.WinUI.Forms;

namespace Fcdbas.WinUI.Controls
{
    [Description("表示 Fcdbase 图片框控件，用来显示图片。")]
    [ToolboxBitmap(typeof(System.Windows.Forms.PictureBox))]
    [ToolboxItemFilter("System.Windows.Forms")]
    public class cPictureEdit : PictureEdit, IReference, IOwningDataSourceBinding, IReadOnly, IValidate, IControl
    {
        public cPictureEdit()
        {
            this.ParseEditValue += new DevExpress.XtraEditors.Controls.ConvertEditValueEventHandler(cPictureEdit_ParseEditValue);
        }
        private bool _isUserKey = true;
        /// <summary>
        /// 是否启用默认的按钮事件
        /// </summary>
        public bool IsUserKey
        {
            get
            {
                return _isUserKey;
            }
            set
            {
                _isUserKey = value;
            }
        }
        protected override bool IsInputKey(System.Windows.Forms.Keys keyData)
        {
            if (!_isUserKey)
            {
                if ((keyData & Keys.Alt) == Keys.Alt)
                {
                    return false;
                }
                switch ((keyData & Keys.KeyCode))
                {
                    case Keys.Up:
                    case Keys.Down:
                        return true;
                }
            }
            return base.IsInputKey(keyData);
        }
        void cPictureEdit_ParseEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
        {
            if (e.Value != null)
            {
                if (e.Value is Image)
                {
                    Bitmap bm = e.Value as Bitmap;
                    e.Value = Fcdbas.Core.Util.BitmapHelper.BitmapToBytes(bm);
                    e.Handled = true;
                }
            }
        }
        
        private cLabel bindLabel;
        public cLabel BindLabel
        {
            get
            {
                return this.bindLabel;
            }
            set
            {
                this.bindLabel = value;
            }
        }
        public string Label
        {
            get
            {
                if (bindLabel != null)
                    return bindLabel.Text;
                else
                    return "";
            }

        }
        //public override ContextMenuStrip ContextMenuStrip
        //{
        //    get
        //    {
        //        if (base.ContextMenuStrip == null)
        //            return new ContextMenuStrip();
        //        else
        //            return base.ContextMenuStrip;
        //    }
        //    set
        //    {
        //        if (value != null)
        //            this.Properties.ShowMenu = false;
        //        base.ContextMenuStrip = value;
        //    }
        //}
        //[Bindable(true)]
        //public Byte[] BigImage
        //{
        //    get
        //    {
        //        if (this.Image == null)
        //            return null;
        //        Bitmap bm = this.Image as Bitmap;
        //        if (bm == null)
        //            return null;
        //        return Fcdbas.Core.Util.BitmapHelper.BitmapToBytes(bm);
                
        //    }
        //    set
        //    {
        //        if (value != null)
        //        {
        //            this.Image = Fcdbas.Core.Util.BitmapHelper.BytesToBitmap(value);
        //        }
        //        else
        //            this.Image = null;
        //    }
        //}
        private string _filePath;
        [Browsable(true)]
        [Category("Fcdbas")]
        [Description("指定绑定的图片文件")]
        [Bindable(true)]
        public string FilePath
        {

            get
            {
                BindingFlags mFieldFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.ExactBinding;
               
                FieldInfo fieldInfo = this.Menu.GetType().GetField("openFile", mFieldFlags);
                if (fieldInfo != null)
                {
                    object obj =fieldInfo.GetValue(this.Menu);
                    if (obj is OpenFileDialog)
                    {
                        OpenFileDialog op = obj as OpenFileDialog;
                        return op.FileName;
                    }
                }
                return _filePath;
            }
            set
            {
                _filePath = value;
                if (!System.IO.File.Exists(value))
                    return;
                //byte[] pic = Fcdbas.Core.Util.FileHelper.g
                this.Image = Image.FromFile(value);
            }
        }
        [Browsable(false)]
        public string FileName
        {
            get
            {
                if (string.IsNullOrEmpty(_filePath))
                    return "";
                return Fcdbas.Core.Util.FileHelper.GetFileNameNoPath(_filePath);
            }
            set
            {

            }
        }
        /// <summary>
        /// 绑定的字段信息
        /// </summary>
        public DataItem DataColumn
        {
            get;
            set;
        }
        #region IReference 成员
        public bool IsDelete
        {
            set
            {
                if (value)
                {
                    Font font = new Font(this.Font, FontStyle.Strikeout);
                    this.Font = font;
                    oldForeColor = this.ForeColor;
                    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.DeleteColor;
                }
                else
                {
                    Font font = new Font(this.Font, FontStyle.Regular);
                    this.Font = font;
                    this.ForeColor = oldForeColor;
                }
            }
        }
        public string Value
        {
            get
            {
                return this.Text;
            }
            set
            {
                this.Text = value;
            }
        }
        private bool _isEditing;
        public void PostEdit()
        {
            //this.RaiseEditValueChanged();
        }
        public bool IsEditing
        {
            get
            {
                return _isEditing;
            }
            set
            {
                _isEditing = value;
                //if (value)
                //{
                //    this.oldForeColor = this.ForeColor;
                //    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.EditColor;
                //}
                //else
                //{
                //    this.ForeColor = oldForeColor;
                //}
            }
        }
        public bool IsReference
        {
            get
            {
                return !string.IsNullOrEmpty(Reference);
            }
        }

        public string Reference
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.Reference;

                return null;
            }
        }

        private string columnName;
        public string Column
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.ColumnName;
                else
                    return columnName;
            }
            set
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    bindingItem.ColumnName = value;
                columnName = value;
            }
        }

        public Type DataType
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.DataType;

                return null;
            }
        }

        public object ReferenceValue
        {
            get
            {
                return this.Text;
            }
        }

        public void SetValue(object value)
        {
            if (value == null ||
                value is DBNull)
                return;

            this.Text = value.ToString();
        }

        #endregion

        private DataItem GetBindingItem()
        {
            return DataColumn;

        }
        
        private DataSourceBinding GetOwningDataSourceBinding()
        {
            DataSourceBinding ds = null;
            if (this.DataBindings["Text"] != null)
                ds = this.DataBindings["Text"].DataSource as DataSourceBinding;
            if (this.DataBindings["EditValue"] != null)
                ds = this.DataBindings["EditValue"].DataSource as DataSourceBinding;
            //if (this.DataBindings["BigImage"] != null)
            //    ds = this.DataBindings["BigImage"].DataSource as DataSourceBinding;
            if(ds == null)
            {
                if (OldBinding != null)
                    return OldBinding.DataSource as DataSourceBinding;
                else
                    return null;
            }
            return ds;
        }
        #region IOwningDataSourceBinding 成员
        private Binding _oldBinding;
        public Binding OldBinding
        {
            get
            {
                return _oldBinding;
            }
            set
            {
                _oldBinding = value;
            }
        }
        [Browsable(false)]
        public DataSourceBinding OwningDataSourceBinding
        {
            get { return GetOwningDataSourceBinding(); }
        }

        [Browsable(false)]
        DataSourceBinding IOwningDataSourceBinding.OwningDataSourceBinding
        {
            get { return OwningDataSourceBinding; }
        }

        [Browsable(false)]
        public DataItem BindingItem
        {
            get
            {
                return GetBindingItem();
            }
        }

        #endregion

        #region IReadOnly 成员

        private Color oldForeColor;
        public bool ReadOnly
        {
            get
            {
                return this.Properties.ReadOnly;
            }
            set
            {
                this.Properties.ReadOnly = value;
                if (value)
                {
                    oldForeColor = this.ForeColor;
                    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.ReadOnlyColor;
                }
                else
                {
                    this.ForeColor = oldForeColor;
                }

            }
        }

        #endregion
        /// <summary>
        /// 触发获取引用字段
        /// </summary>
        private bool FireRef = false;
        protected override void  OnEditValueChanged()
        {
            if (OwningDataSourceBinding != null)
            {
                if (OwningDataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                    return;
                //if (!OwningDataSourceBinding.AllowEdit)
                //    return;
                if (!OwningDataSourceBinding.Session.IsNew && !OwningDataSourceBinding.Session.IsEdit && !OwningDataSourceBinding.Binding && !OwningDataSourceBinding.Session.RecordRefresh)
                {
                    Form frm = WinUI.Common.WinUtil.GetParentForm(this);
                    if (frm != null)
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.AM_DataSourceFieldModified, 1, OwningDataSourceBinding.Identify);
                    IsEditing = true;
                }
                Fcdbas.Core.IEntity en = OwningDataSourceBinding.Current as Fcdbas.Core.IEntity;
                if (en != null)
                {
                    if (EditValue != null)
                    {
                        if (EditValue is Image)
                        {
                            Bitmap bm = EditValue as Bitmap;
                            en[GetBindingItem().ColumnName] = Fcdbas.Core.Util.BitmapHelper.BitmapToBytes(bm);

                        }
                    }
                    else
                        en[GetBindingItem().ColumnName] = null;
                }
            }
           
            FireRef = true;
            base.OnEditValueChanged();
        }

        private Color oldBackColor;
        protected override void OnGotFocus(EventArgs e)
        {
            oldBackColor = this.BackColor;
            this.BackColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.FocusColor;
            base.OnGotFocus(e);
        }

        protected override void OnLostFocus(EventArgs e)
        {
            this.BackColor = oldBackColor;
            if (FireRef)
            {
                BaseForm parentForm = this.FindForm() as BaseForm;
                if (parentForm != null)
                    parentForm.FireOnTextChangedEvent(this);
                FireRef = false;
            }
            base.OnLostFocus(e);
        }

        protected override void OnEnter(EventArgs e)
        {
            BaseForm parentForm = this.FindForm() as BaseForm;
            if (parentForm != null)
                parentForm.FireOnEnterEvent(this);

            base.OnEnter(e);
        }
        public bool Validate()
        {
            DataSourceBinding ownerDataSourceBinding = GetOwningDataSourceBinding();
            if (DataColumn != null &&
                   DataColumn.Required &&
                   this.EditValue == null)
            {
                WinUI.Forms.BaseForm form = this.FindForm() as WinUI.Forms.BaseForm;
                if (form != null)
                    form.ShowMessage("字段[%%1]不能为空！", DataColumn.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
           // return ownerDataSourceBinding.Validate(this.DataColumn.ColumnName, this.Text);
        }
    }
}
